package com.inspur.edp.web.frontendproject.zerocode.operation.webdevjson.specific;

import com.inspur.edp.i18n.resource.api.metadata.LinguisticResource;
import com.inspur.edp.i18n.resource.api.metadata.ResourceItem;
import com.inspur.edp.i18n.resource.api.metadata.ResourceMetadata;
import com.inspur.edp.lcm.metadata.api.entity.*;
import com.inspur.edp.lcm.metadata.api.service.NoCodeService;
import com.inspur.edp.web.common.JITEngineConstants;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.metadata.MetadataTypeEnum;
import com.inspur.edp.web.formmetadata.i18n.constant.I18nResourceConstant;
import com.inspur.edp.web.formmetadata.service.FormMetadataService;
import com.inspur.edp.web.frontendproject.zerocode.ZeroCodeFormRefMetadataParameter;
import com.inspur.edp.web.jitengine.i18nresource.GenerateResourceManager;
import com.inspur.edp.web.jitengine.i18nresource.GeneratedI18nResourceList;
import io.iec.edp.caf.common.JSONSerializer;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class FormResourceOperation {

    /**
     * 保存
     *
     * @param formParameter
     */
    public void save(GspMetadata formMd, String wevDevPath) {

        // 英文
        GeneratedI18nResourceList enGeneratedResourceList = new GeneratedI18nResourceList();

        // 繁体
        GeneratedI18nResourceList zhCHTGeneratedResourceList = new GeneratedI18nResourceList();

        // 简体中文
        GeneratedI18nResourceList zhCHSGeneratedResourceList = new GeneratedI18nResourceList();

        // en-UK
        GeneratedI18nResourceList enUKGeneratedResourceList = new GeneratedI18nResourceList();

        // en-US
        GeneratedI18nResourceList enUSGeneratedResourceList = new GeneratedI18nResourceList();

        // 构造对应的国际化资源项
        GenerateResourceManager.generateI18nResource(formMd, null, enGeneratedResourceList, "", I18nResourceConstant.En);
        GenerateResourceManager.generateI18nResource(formMd, null, zhCHTGeneratedResourceList, "", I18nResourceConstant.ZH_CHT);
        GenerateResourceManager.generateI18nResource(formMd, null, zhCHSGeneratedResourceList, "", I18nResourceConstant.ZH_CHS);
        GenerateResourceManager.generateI18nResource(formMd, null, enUKGeneratedResourceList, "", I18nResourceConstant.EN_UK);
        GenerateResourceManager.generateI18nResource(formMd, null, enUSGeneratedResourceList, "", I18nResourceConstant.EN_US);

        GenerateResourceManager.generateI18nJsonFile(enGeneratedResourceList,
                FileUtility.combineOptional(wevDevPath, "i18n", formMd.getHeader().getCode().toLowerCase(), "i18n"),
                "");
        GenerateResourceManager.generateI18nJsonFile(zhCHTGeneratedResourceList,
                FileUtility.combineOptional(wevDevPath, "i18n", formMd.getHeader().getCode().toLowerCase(), "i18n"),
                I18nResourceConstant.ZH_CHT + ".json");
        GenerateResourceManager.generateI18nJsonFile(enUKGeneratedResourceList,
                FileUtility.combineOptional(wevDevPath, "i18n", formMd.getHeader().getCode().toLowerCase(), "i18n"),
                I18nResourceConstant.EN_UK + ".json");
        GenerateResourceManager.generateI18nJsonFile(enUSGeneratedResourceList,
                FileUtility.combineOptional(wevDevPath, "i18n", formMd.getHeader().getCode().toLowerCase(), "i18n"),
                I18nResourceConstant.EN_US + ".json");

        GenerateResourceManager.generateZhI18nJsonFile(zhCHSGeneratedResourceList, wevDevPath,
                String.format("%1$s%2$s", formMd.getHeader().getFileName().toLowerCase(), JITEngineConstants.ResourceJsonFile));
    }

    public static void generateI18nResource(List<I18nResource> resourceList,
                                            GeneratedI18nResourceList i18nResourceList,
                                            String keyPrefix,
                                            String language) {
        try {
            if (!resourceList.isEmpty()) {
                resourceList = resourceList
                        .stream()
                        .filter((t) -> language.equals(t.getLanguage()))
                        .collect(Collectors.toList());
            }
            GenerateResourceManager.generateResourceList(i18nResourceList, keyPrefix, resourceList);
        } catch (Exception ex) {
            //排除掉找不到对应的资源文件的异常
            if (ex.getMessage() != null && !ex.getMessage().contains("Can't Find Metadata")) {
                WebLogger.Instance.info(ex.getMessage(), GenerateResourceManager.class.getName());
            } else {
                WebLogger.Instance.error(ex);
                throw ex;
            }
        }
    }

    public static List<I18nResource> getI18nResource(GspMetadata formMd) {
        //参数校验及变量初始化

        List<MetadataReference> metadataReferences = formMd.getRefs();     //基础元数据依赖的资源元数据列表
        NoCodeService noCodeService = SpringBeanUtils.getBean(NoCodeService.class);

        if (metadataReferences != null && !metadataReferences.isEmpty()) {
            List<I18nResource> i18nResources = new ArrayList<>();   //语言资源集
            ResourceMetadata metadata;
            //根据依赖的资源元数据列表，遍历找到对应的资源元数据+多语资源元数据
            for (MetadataReference gspMetadata : metadataReferences) {
                if ("ResourceMetadata".equals(gspMetadata.getDependentMetadata().getType())) {
                    //取得资源元数据
                    GspMetadata resourceMd = noCodeService.getMetadata(gspMetadata.getDependentMetadata().getId());
                    //资源元数据内容为空，返回空
                    if (resourceMd != null && resourceMd.getContent() != null) {
                        metadata = (ResourceMetadata) resourceMd.getContent();
                        String mdStr = JSONSerializer.serialize(metadata);
                        ResourceMetadata cloneResourceMd = JSONSerializer.deserialize(mdStr, ResourceMetadata.class);
                        i18nResources.add(convertToI18nResource(cloneResourceMd, cloneResourceMd.getOriginalLanguage()));

                        List<MetadataReference> lResourceRefs = resourceMd.getRefs();
                        if (lResourceRefs != null && !lResourceRefs.isEmpty()) {
                            for (MetadataReference lResourceRef : lResourceRefs) {
                                if ("LinguisticResource".equals(lResourceRef.getDependentMetadata().getType())) {
                                    GspMetadata lMetadata = noCodeService.getMetadata(lResourceRef.getDependentMetadata().getId());
                                    LinguisticResource lresource = null;
                                    if (lMetadata != null && lMetadata.getContent() != null) {
                                        lresource =(LinguisticResource) lMetadata.getContent();
                                        i18nResources.add(merge(cloneResourceMd, lresource));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return i18nResources;
        } else return null;
    }

    private static I18nResource convertToI18nResource(ResourceMetadata metadata, String language) {

        //null直接返回null
        if (metadata == null) return null;

        //资源元数据转换为国际化资源
        I18nResource i18nResource = new I18nResource();
        i18nResource.setStringResources(new I18nResourceItemCollection());
        i18nResource.setImageResources(new I18nResourceItemCollection());
        i18nResource.setLanguage(language);
        //文本资源
        if (metadata.getStringResources() != null && !metadata.getStringResources().isEmpty()) {
            for (ResourceItem text : metadata.getStringResources()) {
                I18nResourceItem item = new I18nResourceItem();
                item.setKey(text.getId());
                item.setValue(text.getValue());
                item.setComment(text.getComment());
                i18nResource.getStringResources().add(item);
            }
        }
        //图片资源
        if (metadata.getImageResources() != null && metadata.getImageResources().size() != 0) {
            for (ResourceItem image : metadata.getImageResources()) {
                I18nResourceItem item = new I18nResourceItem();
                item.setKey(image.getId());
                item.setValue(image.getValue());
                item.setComment(image.getComment());
                i18nResource.getImageResources().add(item);
            }
        }
        return i18nResource;
    }

    /**
     * 资源元数据metadata 和 多语资源lresource 合并
     *
     * @param metadata  资源元数据
     * @param lresource 多语资源
     * @return I18nResource
     */
    public static I18nResource merge(ResourceMetadata metadata, LinguisticResource lResource) {

        //资源元数据和多语资源校验
        if (metadata == null || lResource == null) {
            return convertToI18nResource(metadata, "zh-CHS");
        }

        //合并文本
        for (ResourceItem text : metadata.getStringResources()) {
            for (ResourceItem lText : lResource.getStringResources()) {
                if (text.getId().equals(lText.getId())) {
                    text.setValue(lText.getValue());
                    break;
                }
            }
        }
        //合并图片
        for (ResourceItem image : metadata.getImageResources()) {
            for (ResourceItem lImage : lResource.getImageResources()) {
                if (image.getId().equals(lImage.getId())) {
                    image.setValue(lImage.getValue());
                    break;
                }
            }
        }
        //将资源元数据转化为国际化资源
        return convertToI18nResource(metadata, lResource.getLanguage());
    }
}
